#pragma once
#include <iostream>
#include <set>
#include <string>
#include "InetAddr.hpp"
#include "log.hpp"

using namespace LogModule;
class Commend
{
public:
    Commend()
    {
        _commends.insert("ls");
        _commends.insert("whoami");
        _commends.insert("touch text.txt");
        _commends.insert("ls -al");
        _commends.insert("pwd");
        _commends.insert("cd ..");
    }
    ~Commend()
    {
    }
    bool IsSafe(std::string &cmd)
    {
        auto pos = _commends.find(cmd);

        return !(pos == _commends.end());
    }
    std::string Exuate(std::string cmd, InetAddr &cli)
    {
        // 1.验证合法性
        bool ret = IsSafe(cmd);
        if (ret)
        {
            // 2.执行命令并返回结果
            FILE *get = popen(cmd.c_str(), "r");
            if (get == nullptr)
            {
                LOG(LogLevel::ERROR) << "popen fail!!";
                perror("reason");
                exit(2);
            }
            char buffer[1024];
            std::string result;
            // 读到末尾fgets会返回nullptr
            while (fgets(buffer, sizeof(buffer), get))
            {
                result += buffer;
            }
            LOG(LogLevel::INFO)<<cli.Ip()<<cli.Port()<<"执行了一个命令"<<cmd;
            fclose(get);
            return result;
        }
        else
        {
            return "禁止命令，无权访问！！";
        }
    }

private:
    std::set<std::string> _commends;
};